package com.inventive.jmscache.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.transaction.xa.XAResource;
import java.util.List;
import java.util.Iterator;

/**
 * User: grant
 */
@Component
@Qualifier("JmsCacheServer")
public class JmsCacheServerImpl implements JmsCacheServer {

    @Autowired
    @SuppressWarnings({"UnusedDeclaration"})
    private JmsCacheConfiguration jmsCacheConfiguration;
    @Autowired
    @SuppressWarnings({"UnusedDeclaration"})
    private DestinationsCache destinationsCache;

    @PostConstruct
    public void start() {
        jmsCacheConfiguration.getBackend().start();
        for (String queue : jmsCacheConfiguration.getQueues()) {
            destinationsCache.addQueue(queue);
        }
        for (String topic : jmsCacheConfiguration.getTopics()) {
            destinationsCache.addTopic(topic);
        }
    }

    public void stop() {
        jmsCacheConfiguration.getBackend().stop();
    }

    public BackendQueue getQueue(String name) {

        destinationsCache.checkContainsQueue(name);
        return jmsCacheConfiguration.getBackend().getQueue(name);
    }

    public BackendTopic getTopic(String name) {

        destinationsCache.checkContainsTopic(name);
        return jmsCacheConfiguration.getBackend().getTopic(name);
    }

    public void startTransaction() {
        jmsCacheConfiguration.getBackend().startTransaction();
    }

    public void commitTransaction() {
        jmsCacheConfiguration.getBackend().commitTransaction();
    }

    public void rollbackTransaction() {
        jmsCacheConfiguration.getBackend().rollbackTransaction();
    }

    public List<JmsCacheMessage> getMessages(String queueName, String messageSelector) {
        return jmsCacheConfiguration.getBackend().getMessages(queueName, messageSelector);
    }

//    @Override
    public Iterator<JmsCacheMessage> getMessageIterator(String queueName, String messageSelector) {
        return jmsCacheConfiguration.getBackend().getMessages(queueName, messageSelector).iterator();
    }

    public List<String> getSubscriptionsForTopic(String name) {
        return jmsCacheConfiguration.getBackend().getSubscriptionsForTopic(name);
    }

    public void addMessageIdToSubscription(String subscriptionId, String messageId) {
        jmsCacheConfiguration.getBackend().addMessageIdToSubscription(subscriptionId, messageId);
    }

    public XAResource getBackendXAResource() {
        return null;
//        return jmsCacheConfiguration.getBackend().
    }
}
